package org.zjvis.datascience.service.audit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.zjvis.datascience.common.dto.AuditDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @description 审计的定时Service
 * @date 2021-08-20
 */
@Component
public class ScheduledService {

    private static final Logger log = LoggerFactory.getLogger(ScheduledService.class);

    @Autowired
    private AuditService auditService;

    //审计数据存入本地内存消息队列中
    private static Queue<AuditDTO> auditQueue = new ConcurrentLinkedQueue<>();

    private static final int BATCH_INSERT_SIZE = 50;

    public static boolean offer(AuditDTO auditDTO) {
        if (auditDTO == null) {
            return false;
        }
        return auditQueue.offer(auditDTO);
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void scheduledInsertAudit() {
        log.info("Scheduled insert auditInfo begin!");
        if (auditQueue.isEmpty()) {
            return;
        }
        List<AuditDTO> auditList = new ArrayList<>();
        int success = 0, total = 0;
        while (true) {
            AuditDTO audit = auditQueue.poll();
            if (audit == null) {
                break;
            } else {
                total++;
                auditList.add(audit);
                if (auditList.size() >= BATCH_INSERT_SIZE) {
                    success += auditService.batchInsert(auditList);
                    auditList.clear();
                }
            }
        }
        if (!auditList.isEmpty()) {
            success += auditService.batchInsert(auditList);
            auditList.clear();
        }
        log.info("Scheduled insert finished. Insert success number is: {}, total: {}", success, total);
    }
}
